package com.espirit.hr;

import java.io.Serializable;
import java.util.Date;

import org.hibernate.type.Type;
import org.springframework.stereotype.Service;

import com.espirit.eap.manager.DefaultEntityInterceptor;
import com.espirit.eap.sa.LoginUserService;
import com.espirit.eap.sa.User;
import com.espirit.finance.core.AcctTerm;
import com.espirit.finance.core.AcctTermCheckAware;
import com.googlecode.cswish.exception.ApplicationException;
import com.googlecode.cswish.struts.spring.ObjectFactory;

@Service
public class HrEntityInteceptor extends DefaultEntityInterceptor{

	private static final long serialVersionUID = -3745003545920606327L;
	private HrSettingService hrSettingService;
	
	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		boolean modified = super.onSave(entity, id, state, propertyNames, types);
		if (entity instanceof EmployeeAware){
			EmployeeAware employeeAware = (EmployeeAware) entity;
			if (employeeAware.getDepartment() == null && employeeAware.getEmployee() != null){
				employeeAware.setDepartment(employeeAware.getEmployee().getDepartment());
			}
		}
		if (entity instanceof VersionAware){
			LoginUserService userService = getUserService();
			if (userService.getLoginUser() != null){
				VersionAware versionAware = (VersionAware) entity;
				versionAware.setCreated((User)userService.getLoginUser().getUserEx());
				versionAware.setCreatedOn(new Date());
			}
		}

		return modified;
	}
	
	@Override
	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
			String[] propertyNames, Type[] types) {
		boolean modified = super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
		if (entity instanceof EmployeeAware){
			EmployeeAware employeeAware = (EmployeeAware) entity;
			if (employeeAware.getDepartment() == null && employeeAware.getEmployee() != null){
				employeeAware.setDepartment(employeeAware.getEmployee().getDepartment());
			}
		}
		
		return modified;
	}
	
	@Override
	protected AcctTerm getAcctTerm() {
		return  getHrSettingService().getHrSetting().getCurrentAcctTerm();
	}
	
	protected HrSettingService getHrSettingService() {
		if (hrSettingService == null) {
			hrSettingService = ObjectFactory.getInstance().getBean(HrSettingService.class, true);
		}
		return hrSettingService;
	}
}
